package kvoog.arkanoid.rendering;

import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Mapper;
import com.artemis.systems.EntityProcessingSystem;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion;
import com.badlogic.gdx.utils.Disposable;

public class SpriteRenderingSystem extends EntityProcessingSystem implements Disposable {
	
	private @Mapper ComponentMapper<Transform> trm;
	private @Mapper ComponentMapper<Spatial> spm;

	private SpriteBatch spriteBatch;
	private OrthographicCamera camera;
	private TextureAtlas spriteAtlas;
	private Color oldColor;

	@SuppressWarnings("unchecked")
	public SpriteRenderingSystem(SpriteBatch spriteBatch) {
		super(Aspect.getAspectForAll(Transform.class, Spatial.class));
		this.spriteBatch = spriteBatch; 
	}

	@Override
	protected void initialize() {
		super.initialize();

		spriteAtlas = new TextureAtlas("sprites/arkanoid_sprites.pack");
		
		camera = new OrthographicCamera(8, 4.8f);
		camera.translate(4, 2.4f);
		camera.update();
	}	

	@Override
	protected void inserted(Entity e) {
		super.inserted(e);
	}

	@Override
	protected void removed(Entity e) {
		super.removed(e);
	}

	@Override
	protected void begin() {
		super.begin();
		
		spriteBatch.setProjectionMatrix(camera.combined);
		spriteBatch.enableBlending();
		spriteBatch.begin();
		oldColor = spriteBatch.getColor(); 
	}

	@Override
	protected void end() {
		super.end();
		spriteBatch.setColor(oldColor);
		spriteBatch.end();
	}

	@Override
	protected void process(Entity e) {
		Spatial spatial = spm.get(e);
		Transform transform = trm.get(e);

		AtlasRegion region = spriteAtlas.findRegion(spatial.name);
		spriteBatch.setColor(spatial.color);
		spriteBatch.draw(region, transform.position.x-transform.width/2, transform.position.y-transform.height/2, transform.width, transform.height);
	}

	@Override
	public void dispose() {
		spriteAtlas.dispose();
	}

}
